package io.plus.user_interface.server.command.command_handler;

import io.plus.interactive.AsynchronousSocketChannelContext;
import io.plus.user_interface.common.Status;
import io.plus.user_interface.common.io;
import io.plus.user_interface.common.packet.CloseRequestMessage;
import io.plus.user_interface.common.packet.Command;
import io.plus.user_interface.common.packet.ResponseMessage;
import io.plus.user_interface.common.protocol.PacketImpl;
import io.plus.user_interface.common.utils.ImKit;
import io.plus.user_interface.common.utils.JsonKit;
import io.plus.user_interface.server.command.AbstractCommandHandler;

/**
 * 关闭请求cmd命令处理器
 */
public class CloseCommandHandler extends AbstractCommandHandler {
    @Override
    public Command command() {
        return Command.close_request;
    }

    @Override
    public PacketImpl handler(PacketImpl packet, AsynchronousSocketChannelContext asynchronousSocketChannelContext) throws Exception {
        CloseRequestMessage closeReqBody = null;
        try {
            closeReqBody = JsonKit.toBean(packet.getBody(), CloseRequestMessage.class);
        } catch (Exception e) {
            //关闭请求消息格式不正确
            return ImKit.convertResponsepPacket(new ResponseMessage(Command.close_request, Status.C10020), asynchronousSocketChannelContext);
        }
        if (closeReqBody == null || closeReqBody.getUserId() == null) {
            io.remove(asynchronousSocketChannelContext, "收到关闭请求");
        } else {
            String userId = closeReqBody.getUserId();
            io.remove(userId, "收到关闭请求!");
        }
        return ImKit.convertResponsepPacket(new ResponseMessage(Command.close_request, Status.C10021), asynchronousSocketChannelContext);
    }
}
